package com.dmyang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dmyang.dao.JedisClientSingle;
import com.dmyang.entity.Message;
import com.dmyang.vo.GroupUserVo;
import com.dmyang.vo.Respose;
import com.dmyang.vo.UserVo;
import com.dmyang.websocket.MyWebSocketHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by brss on 2018/5/12.
 */
@Controller
@RequestMapping("/doctor")
public class DoctorController {


    @RequestMapping("/DDChat")
    public String DDChat(){
        return "DDChat";
    }

    @RequestMapping("/initDoc")
    public String docInit(){
        return "docInit";
    }

    @RequestMapping("/docInitAddSession")
    public String addSession(HttpSession session, @RequestParam("name") String name,
                             @RequestParam String primaryKey,
                             @RequestParam String role){
        session.setAttribute("pk",primaryKey);
        session.setAttribute("name",name);
        session.setAttribute("role",role);
        return "DPChat_doc";
    }

    @RequestMapping("/DPChat")
    public String DPChat(){

        return "DPChat_doc";
    }

    /**
     * 在线的医生
     * @param session
     * @return
     */
    @RequestMapping("/onlineDocs")
    @ResponseBody
    public synchronized Respose onlineDocs(HttpSession session){
        Map<String, WebSocketSession> map= MyWebSocketHandler.userSocketSessionMap;
        Set<String> set=map.keySet();
        Iterator<String> it = set.iterator();
        Map<String,String> onlineMap = new ConcurrentHashMap<>();
        while(it.hasNext()){
            //当前请求用户的pk
            String pk = it.next();
            String name = (String) map.get(pk).getAttributes().get("name");
            onlineMap.put(pk,name);
        }
        Set<String> keyset = onlineMap.keySet();
        List<GroupUserVo> onlineList = new ArrayList();
        for (String key : keyset){
            GroupUserVo groupUserVo = new GroupUserVo();
            groupUserVo.setId(key);
            groupUserVo.setUsername(onlineMap.get(key));
            groupUserVo.setAvatar("//res.layui.com/images/fly/avatar/00.jpg");
            groupUserVo.setSign("医生从不用签名");
            onlineList.add(groupUserVo);
        }
        Map m = new HashMap();
        GroupUserVo g1 = new GroupUserVo();
        g1.setId("9999");
        g1.setUsername("管理员");
        g1.setAvatar("//res.layui.com/images/fly/avatar/00.jpg");
        g1.setSign("医生从不用签名");
        m.put("owner",g1);
        m.put("members",onlineList.size());
        m.put("list",onlineList);
        Respose respose = new Respose();
        respose.setCode(0);
        respose.setData(m);
        respose.setMsg("正常");
        return respose;
    }

    /**
     * 这个函数是被医生请求的
     * @param session
     * @param reqPk 请求用户的主键
     * @return 未接诊患者（最多三人）
     */

    @RequestMapping("/waitPatList")
    @ResponseBody
    public synchronized List<UserVo> onlineusers(HttpSession session, @RequestParam String reqPk){
        Map<String, WebSocketSession> map= MyWebSocketHandler.userSocketSessionMap;
        Map<String, List<UserVo>> relation_doc = MyWebSocketHandler.relation_doc;
        Map<String, List<UserVo>> relation_pat = MyWebSocketHandler.relation_pat;
        return relation_doc.get(reqPk);
    }

    /**
     * 医生诊断完成，结束诊断
     * @return
     */
    @RequestMapping("/stopTreat")
    public String stopTreat(HttpSession session, @RequestParam String reqPk){
        Map<String, WebSocketSession> map= MyWebSocketHandler.userSocketSessionMap;
        ArrayBlockingQueue doctorQueue = MyWebSocketHandler.doctorQueue;
        ArrayBlockingQueue patientQueue = MyWebSocketHandler.patientQueue;
        Map<String, List<UserVo>> relation_doc = MyWebSocketHandler.relation_doc;
        Map<String, List<UserVo>> relation_pat = MyWebSocketHandler.relation_pat;

        //修改websocketsesson状态
        /*int treatNum = (int) map.get(reqPk).getAttributes().get("treatNum");
        if (treatNum==3)
            map.get(reqPk).getAttributes().put("treatNum",0);
        map.get(reqPk).getAttributes().put("isBusy",false);*/
        if ( relation_doc.size() != 0 ){
            for (UserVo userVo : relation_doc.get(reqPk)){//userVo为这个医生的病人
                //给每个病人发送消息
                WebSocketSession webSocketSession = map.get(userVo.getId());
                if ( webSocketSession != null && webSocketSession.isOpen() ){
                    Message msg= new Message();
                    msg.setFrom(reqPk);
                    msg.setFromAvatar("//res.layui.com/images/fly/avatar/00.jpg");
                    msg.setFromName((String) map.get(reqPk).getAttributes().get("name"));
                    msg.setText("系统消息：医生已经选择结束诊断，本次诊断已经结束！");
                    msg.setDate(new Date());
                    try {
                        webSocketSession.sendMessage(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //map.get(userVo.getId()).getAttributes().put("isTreated",true);
                //删除病人的消息队列
                //patientQueue.remove(userVo);
                //清空这个医生所咨询的所有病人的relation_pat
                relation_pat.remove(userVo.getId());
                //删除病人的socket
                try {
                    if (map.get(userVo.getId())!=null && map.get(userVo.getId()).isOpen() )
                        map.get(userVo.getId()).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                map.remove(userVo.getId());
            }
        }

        UserVo userVo = new UserVo();
        userVo.setName((String) map.get(reqPk).getAttributes().get("name"));
        userVo.setId(reqPk);
        userVo.setType("kefu");
        userVo.setAvatar("//res.layui.com/images/fly/avatar/00.jpg");

        doctorQueue.remove(userVo);
        doctorQueue.remove(userVo);
        doctorQueue.remove(userVo);
        //清空relation_doc
        relation_doc.remove(reqPk);
        try {
            if (map.get(reqPk) != null && map.get(reqPk).isOpen() )
                map.get(reqPk).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.remove(reqPk);//把医生的websocket删除
        return "DPChat_doc";
    }

    /*@RequestMapping("/waitPatList")
    @ResponseBody
    public synchronized List<UserVo> onlineusers(HttpSession session, @RequestParam String reqPk){
        Map<String, WebSocketSession> map= MyWebSocketHandler.userSocketSessionMap;
        Set<String> set=map.keySet();
        Iterator<String> it = set.iterator();
        Map<String,String> onlineMap = new ConcurrentHashMap<>();
        //List<UserVo> onlineList = new ArrayList();//存放最终需要的在线的，满足条件的用户
        int chatNum = 0;//此医生已经和几个用户在聊天了，初始为0
        //获取chatWith
        List chatWithList = (List) map.get(reqPk).getAttributes().get("chatWith");
        if (chatWithList.size() != 0 ){
            //证明这个医生已经和某几个病人在聊天了。
            chatNum = chatWithList.size(); //修改聊天数
        }
        //如果可以从redis中取到值，则证明两人已经建立聊天

        while(it.hasNext()){
            //当前请求用户的pk
            //String nowUserPk = (String) session.getAttribute("pk");
            String pk = it.next();
            String name = (String) map.get(pk).getAttributes().get("name");
            String role = (String) map.get(pk).getAttributes().get("role");

            boolean isTreated=true;
            if (role.equals("patient")){
                isTreated = (boolean)map.get(pk).getAttributes().get("isTreated");
            }
            //把当前访问的人从在线列表中去除 ,把医生剔除,把已经被接诊的患者删除
            if (!pk.equals(reqPk) && role.equals("patient") && !isTreated)
                onlineMap.put(pk,name);
        }
        Set<String> keyset = onlineMap.keySet();

        for (String key : keyset){
            if (chatNum==4)
                break;//只要3个人
            for (Object u : chatWithList){//找出不在chatWithList 的 满足要求的用户
                UserVo user = (UserVo)u;
                if (!user.getId().equals(key)){
                    chatNum++;
                    UserVo userVo = new UserVo();
                    userVo.setId(key);
                    userVo.setName(onlineMap.get(key));
                    userVo.setType("kefu");
                    userVo.setAvatar("//res.layui.com/images/fly/avatar/00.jpg");
                    //onlineList.add(userVo);
//            把患者状态修改为已接诊
                    map.get(key).getAttributes().put("isTreated",true);
                    chatWithList.add(userVo);

                    //给患者添加chatWithList
                    List patList = (List) map.get(key).getAttributes().get("chatWith");

                }
            }

        }
        map.get(reqPk).getAttributes().put("chatWith",chatWithList);
        //把医生状态修改为繁忙
        int treatNum = (int) map.get(reqPk).getAttributes().get("treatNum");
        treatNum = chatWithList.size();
        map.get(reqPk).getAttributes().put("treatNum",chatWithList.size());
        if (treatNum >= 3)
            map.get(reqPk).getAttributes().put("isBusy",true);
        return chatWithList;
    }*/
}
